import { constantRouterMap , asyncRouterMap } from '@/router'

/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.power) {
    if((route.meta.power.toString()).indexOf(roles) != -1){
      return true
    }else{
      return false
    }
  }else{
    return true
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */

 
function filterAsyncRouter(asyncRouterMap, roles) {
  // console.log(asyncRouterMap,'11111')
  const accessedRouters = asyncRouterMap.filter(route => {
    // console.log(route,'route111')
    if (hasPermission(roles, route)) {
      if (route.children && route.children.length > 0) {
        // console.log('zou le zheli')
        route.children = filterAsyncRouter(route.children, roles)
        // console.log(route.children,'children')
      }else{

      }
      return true
    }else{
      return false
    }
  })
  return accessedRouters
}


const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {

    GenerateRoutes({ commit }, roles) {
      // console.log(roles,'权限')
      return new Promise(resolve => {
        let accessedRouters
        accessedRouters = filterAsyncRouter(asyncRouterMap, roles)
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission